<!-- 查看电子证书 -->
<template>
  <el-dialog
    :title="dialogTitle"
    :visible="visible"
    width="600px"
    custom-class="view-certificate-dialog"
    append-to-body
    @close="onClose"
  >
    <div class="certificate-container">
      <!-- 当前证书背景图 -->
      <div class="certificate-bg" ref="certificateBg">
        <div class="certificate-content" :style="previewStyle">
          <div
            v-for="field in currentCertificateFields"
            :key="field.fieldKey"
            class="dynamic-text"
            :style="getFieldStyle(field)"
          >
            {{ getFieldContent(field) }}
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="success" @click="handleDownload" :loading="downloading"
          >下载证书</el-button
        >
        <el-button @click="handleSend">发送证书</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
// 导入工具类
import CertificateDownloader from "../../../components/Certificate/issue/certificateDownloader";

export default {
  name: "ViewCertificateDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    templateData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      currentPage: 1,
      dialogTitle: "查看电子证书",
      localCertificateData: [],
      downloading: false,
    };
  },
  computed: {
    certificates() {
      return this.localCertificateData || [];
    },
    currentCertificate() {
      return this.certificates[this.currentPage - 1] || {};
    },
    currentCertificateBgUrl() {
      return (
        this.currentCertificate.certificateTemplateDto?.backgroundUrl || ""
      );
    },
    //解析字段
    currentCertificateFields() {
      const templateDto = this.currentCertificate.certificateTemplateDto;
      if (!templateDto) return [];

      const fields = templateDto.certificateFieldList || [];
      if (!fields.length) return [];

      return fields.filter((f) => f.fieldKey && f.fieldLabel);
    },
    totalPages() {
      return this.certificates.length;
    },
    previewStyle() {
      const templateDto = this.currentCertificate.certificateTemplateDto;
      if (!templateDto) return {};

      const style = {};

      // 设置背景颜色
      if (templateDto.backgroundColor) {
        style.backgroundColor = templateDto.backgroundColor;
      }

      // 设置边框
      if (templateDto.borderColor) {
        style.border = `1px solid ${templateDto.borderColor}`;
      }

      // 如果有背景图片路径，则设置背景图片
      if (this.currentCertificateBgUrl) {
        style.backgroundImage = `url(${this.resolveImageUrl(
          this.currentCertificateBgUrl
        )})`;
        style.backgroundSize = "cover";
        style.backgroundRepeat = "no-repeat";
        style.backgroundPosition = "center";
      }

      return style;
    },
  },
  watch: {
    templateData: {
      handler(newVal) {
        if (newVal) {
          this.localCertificateData = newVal;
        }
      },
      immediate: true,
    },
  },
  methods: {
    open(data) {
      // 处理传入的数据，确保是普通数组
      const processedData = Array.isArray(data)
        ? [...data]
        : Array.isArray(this.templateData)
        ? [...this.templateData]
        : [];
      this.localCertificateData = processedData;
      this.currentPage = 1;
      console.log("当前证书数据", this.currentCertificate);
    },

    onClose() {
      this.$emit("update:visible", false);
      this.$emit("close");
    },

    handlePageChange(page) {
      this.currentPage = page;
    },

    getFieldStyle(field) {
      return {
        fontFamily: field.fontFamily || "SimHei",
        fontSize: (field.fontSize || 18) + "px",
        color: field.fontColor || "#000000",
        fontWeight: field.fontWeight || "normal",
        fontStyle: field.italic === "true" ? "italic" : "normal",
        textDecoration: field.underline === "true" ? "underline" : "none",
        textAlign: field.textAlign || "center",
        lineHeight: field.lineHeight || 1.2,
        letterSpacing: (field.letterSpacing || 0) + "px",
        position: "relative",
        margin: "10px 0",
        padding: "5px",
      };
    },

    getFieldContent(field) {
      // 根据当前证书数据返回字段的值
      const currentCert = this.currentCertificate;
      if (!currentCert) return "未填写";

      // 优先使用当前证书的实际数据，其次是模板示例数据
      switch (field.fieldKey) {
        case "studentName":
          return currentCert.studentName || field.exampleOne || "未填写";
        case "issueDate":
          return currentCert.issueDate || field.exampleOne || "未填写";
        case "validityEnd":
          return currentCert.validityEnd || field.exampleOne || "未填写";
        case "certificateNo":
          return currentCert.certificateNo || field.exampleOne || "未填写";
        case "createdBy":
          return currentCert.createdBy || field.exampleOne || "未填写";
        default:
          // 尝试从当前证书中获取对应字段的值
          if (currentCert[field.fieldKey]) {
            return currentCert[field.fieldKey];
          }
          return field.exampleOne || "未填写";
      }
    },

    async handleDownload() {
      this.downloading = true;
      try {
        // 直接使用工具类的方法下载当前证书
        await CertificateDownloader.downloadSingleCertificate(
          this.currentCertificate
        );
        this.$message.success("证书下载成功！");
        this.$emit("download", this.currentCertificate);
      } catch (error) {
        console.error("下载证书失败:", error);
        this.$message.error("证书下载失败，请重试");
      } finally {
        this.downloading = false;
      }
    },
    handleSend() {
      this.$message.success("证书已发送！");
      this.$emit("send", this.currentCertificate);
    },

    // 解析图片URL，处理相对路径和绝对路径
    resolveImageUrl(url) {
      // 如果是完整的URL(包含协议)，则直接返回
      if (url.startsWith("http://") || url.startsWith("https://")) {
        return url;
      }

      // 如果是相对路径，则添加基础路径
      if (url.startsWith("/")) {
        // 假设后端资源服务地址为 /api
        return `/api${url}`;
      }

      // 其他情况也加上/api前缀
      return `/api/${url}`;
    },
  },
};
</script>

<style scoped>
.view-certificate-dialog {
  border-radius: 8px;
}

.certificate-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.certificate-bg {
  position: relative;
  width: 500px;
  height: 750px;
  overflow: hidden;
  box-sizing: border-box;
  /* 确保证书有明确的背景 */
  background: white;
}

.certificate-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
  /* 确保背景图片正常显示 */
  background-size: cover !important;
  background-repeat: no-repeat !important;
  background-position: center !important;
}

.dynamic-text {
  display: inline-block;
  white-space: nowrap;
  user-select: none;
  pointer-events: none;
  padding: 5px;
  width: 100%;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  justify-content: center;
}
</style>